package com.smartsaas.ugclivii.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.net.NetUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.smartsaas.ugclivii.api.Api;
import com.smartsaas.ugclivii.cd.EleTreeSelectHandler;
import com.smartsaas.ugclivii.cd.MlTreeSelectHandler;
import com.smartsaas.ugclivii.dto.MacZipDto;
import com.smartsaas.ugclivii.dto.ResultDTO;
import com.smartsaas.ugclivii.entity.Electrode;
import com.smartsaas.ugclivii.entity.Job;
import com.smartsaas.ugclivii.entity.MouldParts;
import com.smartsaas.ugclivii.entity.PatternMaterial;
import com.smartsaas.ugclivii.loader.JsonLoader;
import com.smartsaas.ugclivii.ui.UiContext;
import com.smartsaas.ugclivii.utils.FunUtils;
import com.smartsaas.ugclivii.utils.RequestUtils;
import com.smartsaas.ugclivii.utils.ZipUtils;
import nxopen.BasePart;
import nxopen.NXException;
import nxopen.NXMessageBox;
import nxopen.Part;
import nxopen.blockstyler.Button;
import nxopen.blockstyler.Node;
import nxopen.blockstyler.Tree;
import nxopen.uf.UFDisp;
import nxopen.uf.UFModlGeneral;
import nxopen.uf.UFStd;
import nxopen.uf.UFView;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.net.InetAddress;
import java.net.URI;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static nxopen.uf.UFDisp.BackgroundColor.WHITE;
import static nxopen.uf.UFDisp.ImageFormat.PNG;

public class JobRunUtils {

    public static void uploadDesign(){
        try {
            String rootDir = getRootPath();
            if (rootDir == null) return;
            String host = getHost();
            if (host == null) return;
            String partNum = getPartNum();
            if (partNum == null) return;
            Part part = UiContext.SESSION.parts().work();
            final Job job = new Job();
            BasePart.Units units = part.partUnits();
            job.setUnits(units.name());
            UiContext.getInstance().debug("请求版本号！");
            ResultDTO<MacZipDto> resultDTO = Api.applyVersion(host, "/plugin/anno/apply/version", NetUtil.getMacAddress(InetAddress.getLocalHost(),":"), partNum);
            if (!resultDTO.isSuccess()){
                UiContext.getInstance().debugFormat("任务执行失败,%s!",resultDTO.toString());
                return;
            }
            MacZipDto data = resultDTO.getData();
            String version = data.getVersion();
            UiContext.getInstance().debugFormat("版本号：%s", version);
            final String id =data.getJobId();
            final String path = rootDir +"\\uploadDesign\\"+partNum+"\\"+version;
            File file = new File(path);
            if (!file.exists()){
                boolean mkdirs = file.mkdirs();
            }
            UiContext.getInstance().debugFormat("执行路径: %s",path);
            //todo 执行任务

        }catch (Exception e){
            UiContext.getInstance().debug(e);
        }
    }

    private static String getPartNum() throws NXException, RemoteException {
        String partNum = UiContext.getInstance().getPartNumber().value();
        if (StringUtils.isBlank(partNum)){
            UiContext.UI.nxmessageBox().show("系统提示", NXMessageBox.DialogType.INFORMATION, "请先填写零件号!");
            return null;
        }
        return partNum;
    }

    private static String getHost() throws NXException, RemoteException {
        String host=UiContext.getInstance().getConfig().getHost();
        if (StringUtils.isBlank(host)){
            UiContext.UI.nxmessageBox().show("系统提示", NXMessageBox.DialogType.INFORMATION, "请先设置服务器配置!");
            return null;
        }
        return host;
    }

    private static String getRootPath() throws NXException, RemoteException {
        String rootDir = UiContext.getInstance().getWorkDir().path();
        if(StringUtils.isBlank(rootDir)){
            UiContext.UI.nxmessageBox().show("系统提示", NXMessageBox.DialogType.INFORMATION, "请先设置临时工作目录!");
            return null;
        }
        return rootDir;
    }

    /**
     * 模料上穿
     */
    public static void uploadMl() {
        try {
            Button mlUpload = UiContext.getInstance().getMlUpload();
            mlUpload.setEnable(false);
            UFDisp disp = UiContext.UF_SESSION.disp();
            //检查工作目录
            String rootPath = getRootPath();
            //检查服务器配置
            String host =getHost();
            //检查零件号
            String partNum = getPartNum();
            if (StringUtils.isBlank(rootPath)||StringUtils.isBlank(host)||StringUtils.isBlank(partNum)){
                mlUpload.setEnable(true);
                return;
            }
            MouldParts mouldParts = checkParts(partNum);
            if (mouldParts == null){
                UiContext.UI.nxmessageBox().show("请检查模具编号", NXMessageBox.DialogType.INFORMATION, partNum+"不存在!");
                mlUpload.setEnable(true);
                return;
            }
            String bizPath = FunUtils.mkdirForBizPath(rootPath, "material/"+partNum);
            //遍历表单数据
            Tree mlTree = UiContext.getInstance().getMlTree();
            Node node = mlTree.rootNode();
            List<Node> list = new ArrayList<>();
            if (node!=null){
                FunUtils.getAllNode(node,list);
            }
            List<PatternMaterial> materialArrayList = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(list)){
                for (Node nd : list) {
                    String layer = nd.getColumnDisplayText(0);
                    String code = nd.getColumnDisplayText(1);
                    String tag = nd.getColumnDisplayText(2);
                    String x = nd.getColumnDisplayText(3);
                    String y = nd.getColumnDisplayText(4);
                    String z = nd.getColumnDisplayText(5);
                    String px = nd.getColumnDisplayText(6);
                    String py = nd.getColumnDisplayText(7);
                    String pz = nd.getColumnDisplayText(8);
                    String materialName = nd.getColumnDisplayText(9);
                    String number = nd.getColumnDisplayText(10);
                    String supplier = nd.getColumnDisplayText(11);
                    //构造实体
                    PatternMaterial material = new PatternMaterial();
                    material.setPartCode(partNum);
                    material.setLayer(Integer.valueOf(layer));
                    material.setCode(code);
                    material.setNetSize(String.format("%sX%sX%s",x,y,z));
                    material.setBlankSize(String.format("%sX%sX%s",px==null?"0":px,py==null?"0":py,pz==null?"0":pz));
                    material.setMaterial(materialName);
                    material.setNumber(Integer.valueOf(number));
                    material.setSupplier(supplier);
                    //截图，写入文件名称
                    MlTreeSelectHandler.selectBody(tag);
                    int[] q = {0, 0};
                    File file = new File(bizPath, code+".png");
                    disp.createFramedImage(file.getAbsolutePath(),PNG,WHITE, q,1000,0);
                    material.setImage(file.getName());
                    //截图，写入文件名称 end
                    materialArrayList.add(material);
                }
            }
            //导出json
            String json = JSON.toJSONString(materialArrayList);
            JsonLoader.save(new File(bizPath,"ml.json"), json);
            //打包Zip
            long millis = System.currentTimeMillis();
            String jobId=partNum+"V"+millis;
            String zipName = jobId+".zip";
            String zipPath = ZipUtils.zip(bizPath, new File(rootPath,"material").getAbsolutePath(), zipName, partNum);
            UiContext.getInstance().debug(zipPath);
            File file = new File(bizPath);
            FunUtils.deleteFolder(file);
            //上传解压 执行批量操作
            Map<String, String> request = new HashMap<>();
            request.put("jobId", jobId);
            request.put("pcode",partNum);
            URI uri = Api.buildRequest("/plugin/anno/upload/mlzip", request);
            ResultDTO<Void> dto = RequestUtils.postFile(uri, new File(zipPath));
            UiContext.getInstance().debug(dto.toString());
            mlUpload.setEnable(true);
            UiContext.UI.nxmessageBox().show("系统提示", NXMessageBox.DialogType.INFORMATION, "模料上传成功!");
        }catch (Exception e){
            UiContext.getInstance().debug(e);
        }
    }

    public static void uploadEle() {
        try {
            Button button = UiContext.getInstance().getEleUploadButton();
            button.setEnable(false);
            UFDisp disp = UiContext.UF_SESSION.disp();
            //检查工作目录
            String rootPath = getRootPath();
            //检查服务器配置
            String host =getHost();
            //检查零件号
            String partNum = getPartNum();
            if (StringUtils.isBlank(rootPath)||StringUtils.isBlank(host)||StringUtils.isBlank(partNum)){
                button.setEnable(true);
                return;
            }
            MouldParts mouldParts = checkParts(partNum);
            if (mouldParts == null){
                UiContext.UI.nxmessageBox().show("请检查模具编号", NXMessageBox.DialogType.INFORMATION, partNum+"不存在!");
                button.setEnable(true);
                return;
            }
            String bizPath = FunUtils.mkdirForBizPath(rootPath, "ele/"+partNum);
            //遍历表单数据
            Tree eleTree = UiContext.getInstance().getEleTree();
            Node node = eleTree.rootNode();
            List<Node> list = new ArrayList<>();
            if (node!=null){
                FunUtils.getAllNode(node,list);
            }
            List<Electrode> electrodes = new ArrayList<>();
            for (Node nd : list) {
                String layer = nd.getColumnDisplayText(0);
                String code = nd.getColumnDisplayText(1);
                String type = nd.getColumnDisplayText(2);
                String materialName = nd.getColumnDisplayText(3);
                String spark = nd.getColumnDisplayText(4);
                String x = nd.getColumnDisplayText(5);
                String y = nd.getColumnDisplayText(6);
                String z = nd.getColumnDisplayText(7);
                String releaseExcess = nd.getColumnDisplayText(8);
                String num = nd.getColumnDisplayText(9);
                String tag = nd.getColumnDisplayText(10);
                String graphite = nd.getColumnDisplayText(11);
                String machining = nd.getColumnDisplayText(12);
                String supplier = nd.getColumnDisplayText(13);
                Electrode electrode = new Electrode();
                electrode.setPartCode(partNum);
                electrode.setCode(code);
                electrode.setX(x);
                electrode.setY(y);
                electrode.setZ(z);
                electrode.setSpark(spark);
                electrode.setMaterial(materialName);
                electrode.setNumbers(Integer.valueOf(num));
                electrode.setType(type);
                electrode.setSupplier(supplier);
                electrode.setGraphite(graphite);
                electrode.setMachining(machining);
                electrode.setReleaseExcess(releaseExcess);
                electrode.setLayer(Integer.valueOf(layer));
                //截图，写入文件名称
                EleTreeSelectHandler.selectBody(tag);
                int[] q = {0, 0};
                File file = new File(bizPath, code+".png");
                disp.createFramedImage(file.getAbsolutePath(),PNG,WHITE, q,1000,0);
                electrode.setImg(file.getName());
                //截图，写入文件名称 end
                electrodes.add(electrode);
            }
            //导出json
            String json = JSON.toJSONString(electrodes);
            JsonLoader.save(new File(bizPath,"ele.json"), json);
            //打包Zip
            long millis = System.currentTimeMillis();
            String jobId=partNum+"V"+millis;
            String zipName = jobId+".zip";
            String zipPath = ZipUtils.zip(bizPath, new File(rootPath,"ele").getAbsolutePath(), zipName, partNum);
            UiContext.getInstance().debug(zipPath);
            File file = new File(bizPath);
            FunUtils.deleteFolder(file);
            //上传解压 执行批量操作
            Map<String, String> request = new HashMap<>();
            request.put("jobId", jobId);
            request.put("pcode",partNum);
            URI uri = Api.buildRequest("/plugin/anno/upload/elezip", request);
            ResultDTO<Void> dto = RequestUtils.postFile(uri, new File(zipPath));
            UiContext.getInstance().debug(dto.toString());
            button.setEnable(true);
            UiContext.UI.nxmessageBox().show("系统提示", NXMessageBox.DialogType.INFORMATION, "电极上传成功!");
        }catch (Exception e){
            UiContext.getInstance().debug(e);
        }
    }

    public static MouldParts checkParts(String partNum) {
        try{
            Map<String, String> request = MapUtil.builder("partNumber", partNum).build();
            URI uri = Api.buildRequest("/plugin/anno/mould/exist", request);
            ResultDTO<MouldParts> resultDTO = RequestUtils.doGet(uri,new TypeReference<ResultDTO<MouldParts>>(){});
            return resultDTO.getData();
        }catch (Exception e){
            UiContext.getInstance().debug(e);
        }
        return null;
    }
}
